package com.myf.authorize;

import io.jsonwebtoken.Claims;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.lang.NonNull;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Component
public class JwtAuthFilter extends OncePerRequestFilter {
    private final JwtUtil jwtUtil;

    public JwtAuthFilter(JwtUtil jwtUtils) {
        this.jwtUtil = jwtUtils;
    }

    @Override
    protected void doFilterInternal(jakarta.servlet.http.HttpServletRequest request, @NonNull jakarta.servlet.http.HttpServletResponse response, @NonNull jakarta.servlet.FilterChain filterChain) throws IOException, ServletException {
        final String authHeader = request.getHeader("Authorization");
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            filterChain.doFilter(request, response);
            return;
        }
        final String jwt = authHeader.substring(7);
        Claims claims;
        try {
            claims = jwtUtil.getAllClaimsFromToken(jwt);
        } catch (Exception e) {
            filterChain.doFilter(request, response);
            return;
        }
        if (claims == null || claims.isEmpty()) {
            filterChain.doFilter(request, response);
            return;
        }
        try {
            List<GrantedAuthority> authorities = new ArrayList<>();
            authorities.add(new SimpleGrantedAuthority("admin"));
            var user = new AppUser();
            user.id =  claims.get("id", Integer.class);
            user.account =  claims.get("account", String.class);
            user.name =  claims.get("name", String.class);
            user.language =  claims.get("language", String.class);
            user.timezone =  claims.get("timezone", String.class);
            UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
                    user, null, authorities);
            SecurityContextHolder.getContext().setAuthentication(authToken);
        } catch (Exception e) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid User");
            return;
        }
        filterChain.doFilter(request, response);
    }
}
